package com.example.wheather;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tvCity, tvWeather, tvTemp, tvWind, tvPm;
    private ImageView ivIcon;
    private List<WeatherInfo> infoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        infoList = JsonParse.getInstance().getInfosFromJson(MainActivity.this); //获取天气数据
        init();
        getCityData("北京");  //启动时显示北京的天气
    }

    private void init() {
        tvCity = (TextView) findViewById(R.id.tv_city);
        tvWeather = (TextView) findViewById(R.id.tv_weather);
        tvTemp = (TextView) findViewById(R.id.tv_temp);
        tvWind = (TextView) findViewById(R.id.tv_wind);
        tvPm = (TextView) findViewById(R.id.tv_pm);
        ivIcon = (ImageView) findViewById(R.id.iv_icon);
        findViewById(R.id.btn_bj).setOnClickListener(this);
        findViewById(R.id.btn_sh).setOnClickListener(this);
        findViewById(R.id.btn_gz).setOnClickListener(this);
    }

    //获取指定城市的天气信息，调用设置界面数据的方法
    private void getCityData(String city) {
        for (WeatherInfo info : infoList) {
            if (info.getCity().equals(city)) {
                setData(info);
            }
        }
    }

    //设置界面数据
    private void setData(WeatherInfo info) {
        if (info == null)
            return;
        tvCity.setText(info.getCity());
        tvWeather.setText(info.getWeather());
        tvTemp.setText(info.getTemp());
        tvWind.setText("风力：" + info.getWind());
        tvPm.setText("P  M：" + info.getPm());
        switch (info.getWeather()) {
            case "晴转多云":
                ivIcon.setImageResource(R.drawable.cloud_sun);
                break;
            case "多云":
                ivIcon.setImageResource(R.drawable.clouds);
                break;
            case "晴":
                ivIcon.setImageResource(R.drawable.sun);
                break;
        }
    }

    //按钮单击事件回调方法
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_sh:
                getCityData("上海");
                break;
            case R.id.btn_bj:
                getCityData("北京");
                break;
            case R.id.btn_gz:
                getCityData("广州");
                break;
        }
    }
}
